package csc.fresher.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import csc.fresher.dao.UserDAOImpl;
import csc.fresher.domain.User;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */

	// upload settings
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 5; // 5MB
	private static final int MAX_FOLDER_SIZE = 1024 * 1024 * 10; // 10MB
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 20; // 20MB

	public UploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		UserDAOImpl dao = new UserDAOImpl();
		User user = dao.getUser(username);
		String pathStoreFile = "D:\\" + username;
		File pathSF = new File(pathStoreFile);
		if (!pathSF.exists()) {
			pathSF.mkdir();
        }

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// sets memory threshold - beyond which files are stored in disk
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		// sets temporary location to store files
		factory.setRepository(new File(pathStoreFile));

		ServletFileUpload upload = new ServletFileUpload(factory);
		
		// Set max of file upload
		upload.setFileSizeMax(MAX_FILE_SIZE);
		// Set max of request (file + form)
		upload.setSizeMax(MAX_REQUEST_SIZE);

		try {
			List<FileItem> formItems = upload.parseRequest(request);
			if (formItems != null && formItems.size() > 0) {
				for (FileItem item : formItems) {
					if (!item.isFormField()) {
						 String fileName = new File(item.getName()).getName();
	                        String filePath = pathStoreFile + File.separator + fileName;
	                        File storeFile = new File(filePath);
	                        // saves the file on disk
	                        
	                        if (item.getSize() + FileUtils.sizeOfDirectory(pathSF) < MAX_FOLDER_SIZE) {
	                        	 item.write(storeFile);
	 	                        request.setAttribute("messageUpload", "Congratulation !! Upload has been done successfully");
	 	                        user.setUploadDate(new Date());
	 	                        user.setCapacity(user.getCapacity() + item.getSize());
	                        } else {
	                        	request.setAttribute("messageUpload", "Sorry !! Upload has been error");
	                        }
	                       
	                        getServletContext().getRequestDispatcher("/upload.jsp").forward(request, response);
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("messageUpload", "Sorry !! Upload has been error");
			getServletContext().getRequestDispatcher("/upload.jsp").forward(request, response);
		}

	}

}
